from logic.searchDao import searchDao
from .adminBaseHttp import baseHttp,authHttp
from model import model
from logic import articleDao,navlistDao,adminDao
from log import  log
import datetime
from utils import ApiBuild,jwt
from schema import Schema
from .authFilter import authFilter
from .index import index,article,nav
from utils.markdown import MarkDown

#后台登录
class admin_login(baseHttp):
    def get(self):
        self.render("admin/login.html")
    def post(self):
        user = self.get_argument("user")
        password = self.get_argument("password")
        if Schema(str).validate(user) and Schema(str).validate(password):
            try:
                adminobj = adminDao.adminDao.checkAdmin(user, password)
                if not adminobj  == None:
                    jwtstr = jwt.Jwt(adminobj.id,adminobj.user)
                    self.set_cookie("coreid",jwtstr.genJwt())
                    self.redirect("/admin")
            except Exception:
                self.redirect("/admin/login")
        else:
            self.redirect("/admin/login")

class admin_logout(baseHttp):
    def get(self):
        self.clear_all_cookies()
        self.redirect("/admin/login")

#后台
class admin(authHttp):
    @authFilter.auth
    def get(self):
        self.render("admin/index.html")
# 清楚markdown缓存
    def post(self, *args, **kwargs):
        MarkDown().clearCache()
        self.outputJson(ApiBuild.ApiBuild.success())


#后台文章管理
class article(authHttp):
    @authFilter.auth
    def get(self):
        p = self.get_argument("p", 1)
        art = articleDao.articleDao().listAll(p,10)
        self.render("admin/article/index.html",arts=art,page=p,navName = navlistDao.navlistDao().getName)

class article_create(authHttp):
    @authFilter.auth
    def get(self):
        self.render("admin/article/creat.html")

    @authFilter.auth
    def post(self, *args, **kwargs):
        try:
            articleDao.articleDao().clearCache()
            searchDao.clear()
        except Exception:
            log.error(Exception)
        title = self.get_argument("title")
        desc = self.get_argument("desc")
        keyword = self.get_argument("keyword")
        type = int(self.get_argument("type"))
        content = self.get_argument("content")
        if(Schema(int).validate(type) and Schema(str).validate(title) and Schema(str).validate(content) and Schema(str).validate(desc) and Schema(str).validate(keyword)):
            try:
                art = model.article()
                art.content=content
                art.updateDate=datetime.datetime.now()
                art.title=title
                art.tid = type
                art.url = articleDao.articleDao.checkPinYinUrlInDb(art.title)
                art.desc = desc
                art.keyword = keyword
                art.save()
                self.outputJson(ApiBuild.ApiBuild.successWithObject(art.id))
            except IOError:
                log.error(IOError)
                self.outputJson(ApiBuild.ApiBuild.failWithMessage("发生了未知错误"))
        else:
            self.outputJson(ApiBuild.ApiBuild.failWithMessage("数据不能为空"))



class article_update(authHttp):
    @authFilter.auth
    def get(self,aid):
        try:
            art = model.article.objects(id=aid).get()
            self.render("admin/article/update.html",art=art)
        except IOError:
            log.error(IOError)
            self.redirect("/404")

    @authFilter.auth
    def post(self, *args, **kwargs):
        try:
            articleDao.articleDao().clearCache()
            searchDao.clear()
        except Exception:
            log.error(Exception)
        title = self.get_argument("title")
        desc = self.get_argument("desc")
        keyword = self.get_argument("keyword")
        type = int(self.get_argument("type"))
        id = int(self.get_argument("id"))
        content = self.get_argument("content")
        if(Schema(int).validate(id) and Schema(int).validate(type) and Schema(str).validate(title) and Schema(str).validate(content) and Schema(str).validate(desc) and Schema(str).validate(keyword)):
            try:
                art = model.article.objects(id=id).get()
                art.content=content
                art.updateDate=art.updateDate
                art.title=title
                art.keyword = keyword
                art.desc = desc
                art.url = articleDao.articleDao.checkPinYinUrlInDb(title)
                art.tid = type
                art.save()
                self.outputJson(ApiBuild.ApiBuild.successWithObject(art.id))
            except IOError:
                log.error(IOError)
                self.outputJson(ApiBuild.ApiBuild.failWithMessage("发生了未知错误"))
        else:
            self.outputJson(ApiBuild.ApiBuild.failWithMessage("数据不能为空"))


class article_del(authHttp):
    @authFilter.auth
    def get(self,aid):
        try:
            articleDao.articleDao().clearCache()
            searchDao.clear()
        except Exception:
            log.error(Exception)
        arts = model.article.objects(id=aid)
        try:
            if len(arts) > 0:
                art = arts.get()
                art.delete()
                self.outputJson(ApiBuild.ApiBuild.success())
        except Exception:
            self.redirect("/404")


#导航管理
class navlist(authHttp):
    @authFilter.auth
    def get(self):
        self.render("admin/nav/index.html")
class navlist_create(authHttp):
    @authFilter.auth
    def get(self):
        self.render("admin/nav/creat.html")

    @authFilter.auth
    def post(self):
        try:
            navlistDao.navlistDao.clearCache()
        except Exception:
            log.error(Exception)
        title = self.get_argument("title")
        content = self.get_argument("content")
        type = int(self.get_argument("type"))
        name = self.get_argument("name")
        url = self.get_argument("url")
        level = int(self.get_argument("level"))
        if(Schema(str).validate(title) and Schema(str).validate(content) and Schema(str).validate(name) and Schema(str).validate(url) and Schema(int).validate(type) and Schema(int).validate(level)):
            try:
                navn = model.navlist()
                navn.level = level
                navn.type = type
                navn.name = name
                navn.url = url
                navn.title = title
                navn.content = content
                navn.save()
                self.outputJson(ApiBuild.ApiBuild.successWithObject(navn.id))
            except IOError:
                log.error(IOError)
                self.outputJson(ApiBuild.ApiBuild.failWithMessage("发生了未知错误"))
        else:
            self.outputJson(ApiBuild.ApiBuild.failWithMessage("数据不能为空"))
class navlist_update(authHttp):
    @authFilter.auth
    def get(self,aid):
        try:
            nav = model.navlist.objects(id=aid).get()
            self.render("admin/nav/update.html",navobj=nav)
        except IOError:
            log.error(IOError)
            self.redirect("/404")

    @authFilter.auth
    def post(self,nid):
        try:
            navlistDao.navlistDao.clearCache()
        except Exception:
            log.error(Exception)
        nid = int(nid)
        title = self.get_argument("title")
        content = self.get_argument("content")
        type = int(self.get_argument("type"))
        name = self.get_argument("name")
        url = self.get_argument("url")
        level = int(self.get_argument("level"))
        if(Schema(int).validate(nid) and Schema(str).validate(title) and Schema(str).validate(content) and Schema(str).validate(name) and Schema(str).validate(url) and Schema(int).validate(type) and Schema(int).validate(level)):
            try:
                navn = model.navlist.objects(id=nid).get()
                navn.level = level
                navn.type = type
                navn.name = name
                navn.url = url
                navn.title = title
                navn.content = content
                navn.save()
                self.outputJson(ApiBuild.ApiBuild.successWithObject(navn.id))
            except Exception:
                log.error(Exception)
                self.outputJson(ApiBuild.ApiBuild.failWithMessage("发生了未知错误"))
        else:
            self.outputJson(ApiBuild.ApiBuild.failWithMessage("数据不能为空"))


class navlist_del(authHttp):
    @authFilter.auth
    def get(self, nid):
        try:
            navlistDao.navlistDao.clearCache()
        except Exception:
            log.error(Exception)
        navs = model.navlist.objects(id=nid)
        try:
            if len(navs) > 0:
                nav = navs.get()
                nav.delete()
                self.outputJson(ApiBuild.ApiBuild.success())
        except Exception:
            self.redirect("/404")


